/*
 *  Copyright 2009 David Kuhn <david.s.kuhn at gmail.com>.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package com.google.code.teamtools.persist.hibernate;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.google.code.teamtools.persist.IGenericDao;

/**
 * 
 * @author David Kuhn
 */
public abstract class HibernateGenericDao<T, ID extends Serializable> extends
		HibernateDaoSupport implements IGenericDao<T, ID>
{
	private static final Logger LOG = LoggerFactory.getLogger(HibernateGenericDao.class);
	
	private Class<T> persistentClass;
	
	@SuppressWarnings("unchecked")
	protected HibernateGenericDao()
	{
		persistentClass = (Class<T>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
		if (LOG.isInfoEnabled()) LOG.info("Set persistent class to " + persistentClass.getName());
	}
	
	public void clear()
	{
		LOG.warn("Clearing all entities of type [" + getPersistentClass().getName() + "]...");
		getHibernateTemplate().clear();
		if (LOG.isInfoEnabled()) LOG.info("All entites of type [" + getPersistentClass().getName() + "] cleared.");
	}
	
	public int count()
	{
		List<?> list = getHibernateTemplate().find(
                "select count(*) from " + getPersistentClass().getName() + " x");
        Integer count = (Integer) list.get(0);
        return count.intValue();
	}
	
	public void delete(T entity)
	{
		if (LOG.isDebugEnabled()) LOG.debug("Preparing to delete " + entity.toString() + "...");
		getHibernateTemplate().delete(entity);
		if (LOG.isInfoEnabled()) LOG.info(entity.toString() + " deleted.");
	}
	
	public List<T> retrieveAll()
	{
		if (LOG.isDebugEnabled()) LOG.debug("Retrieving all entities from database...");
		return findByCriteria();
	}
	
	@SuppressWarnings("unchecked")
	public List<T> findByExample(T exampleInstance, String... excludeProperty) 
	{
		Criteria criteria = getSession().createCriteria(getPersistentClass());
		Example example = Example.create(exampleInstance);
		for (String exclude : excludeProperty) {
			example.excludeProperty(exclude);
		}
		criteria.add(example);
		return criteria.list();
	}
	
	public T findById(ID id)
	{
		return findById(id, false);
	}
	
	@SuppressWarnings("unchecked")
	public T findById(ID id, boolean lock)
	{
		T entity;
		if (lock) {
			entity = (T) getHibernateTemplate()
					.load(getPersistentClass(), id, LockMode.UPGRADE);
		} else {
			entity = (T) getHibernateTemplate().load(getPersistentClass(), id);
		}
		
		return entity;
	}
	
	public void flush()
	{
		getHibernateTemplate().flush();
	}
	
	public Class<T> getPersistentClass()
	{
		return persistentClass;
	}

	public void save(T entity)
	{
		getHibernateTemplate().saveOrUpdate(entity);
	}
	
	@SuppressWarnings("unchecked")
	protected List<T> findByCriteria(Criterion... criterion) 
	{
		Criteria criteria = getSession().createCriteria(getPersistentClass());
		for (Criterion c : criterion) {
			criteria.add(c);
		}
		return criteria.list();
	}
}
